<?php
/*
Plugin Name: WS News Alerts
Plugin URI: http://icyleaf.com/projects/ws-news-alerts/
Description: Allow user subscription News Alerts after register. First of all, to <a href="options-general.php#users_can_register">ENABLE</a> <strong>Anyone can register</strong>, then click "Manager" right to do more options.
Version: 0.1
Author: icyleaf
Author URI: http://icyleaf.com
*/

// i18n
load_plugin_textdomain('wsna', $path = 'wp-content/plugins/ws-contents');

// define URL
$myabspath = str_replace("\\","/",ABSPATH);  // required for Windows & XAMPP
define('WINABSPATH', $myabspath);
define('WSNAFOLDER', dirname(plugin_basename(__FILE__)));
define('WSNA_ABSPATH', $myabspath.'wp-content/plugins/' . WSNAFOLDER .'/');
define('WSNA_URLPATH', get_option('siteurl').'/wp-content/plugins/' . WSNAFOLDER.'/');

$status = array
(
	'update' => '',
	'error' => ''
);

// Plugin information
class WSNA_Info
{
	var $name = '';
	var $version = '';
	var $author = '';
	var $url = '';
	var $plugin = '';

	function __construct()
	{
		$plugin_data = implode('', file(WSNA_ABSPATH.'ws-news-alerts.php'));
		preg_match("|Plugin Name:(.*)|i", $plugin_data, $this->name);
		preg_match("|Plugin URI:(.*)|i", $plugin_data, $this->url);
		preg_match("|Description:(.*)|i", $plugin_data, $this->description);
		preg_match("|Version:(.*)|i", $plugin_data, $this->version);
		preg_match("|Author:(.*)|i", $plugin_data, $this->author);
		preg_match("|Author URI:(.*)|i", $plugin_data, $this->plugin);

		$this->name = trim($this->name[1]);
		$this->url = trim($this->url[1]);
		$this->description = trim($this->description[1]);
		$this->version = trim($this->version[1]);
		$this->author = trim($this->author[1]);
		$this->plugin = trim($this->plugin[1]);
	}
}

// init
function WSNA_init()
{
	$result = mysql_list_tables(DB_NAME);
	$tables = array();
	while ($row = mysql_fetch_row($result))
		$tables[] = $row[0];
		
	if ( !in_array('ws_news_alerts', $tables) )
		WSNA_install();

	add_action('admin_menu', 'WSNA_add_options_page');
	add_action('admin_head', 'WSNA_admin_head');
	add_filter('plugin_action_links', 'WSNA_plugin_actions', -10, 2);

	// Debug
	//add_filter('the_content', 'WSNA_matching_keywords');

	// Correct action
	add_action('publish_post', 'WSNA_matching_keywords', 5);

}
add_action('init', 'WSNA_init');

// WS News Alerts install
function WSNA_install()
{
	global $wpdb;
	$charset_collate = '';

	// Check MySQL version, then set charset
	if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') )
	{
		if (!empty($wpdb->charset))
			$charset_collate .= " DEFAULT CHARACTER SET $wpdb->charset";

		if (!empty($wpdb->collate))
			$charset_collate .= " COLLATE $wpdb->collate";
	}

	// Create table
	$result = $wpdb->query
	(
		"CREATE TABLE IF NOT EXISTS `ws_news_alerts` (
		`alert_id` INT(11) NOT NULL AUTO_INCREMENT,
		`user_id` VARCHAR(50) NOT NULL,
		`alert_categorie` VARCHAR(255) NOT NULL,
		`alert_keywords` VARCHAR(255) NOT NULL,
		PRIMARY KEY (`alert_id`),
		INDEX (`user_id`),
		INDEX (`alert_keywords`)
		) $charset_collate"
	);

	$result = $wpdb->query
	(
		"ALTER TABLE $wpdb->users ADD COLUMN `user_alerts` tinyint(3) DEFAULT 5"
	);
}

// Add the 'Settings' link to the plugin page
function WSNA_plugin_actions($links, $file) {
	if ($file == WSNAFOLDER .'/ws-news-alerts.php')
		$links[] = '<a href="users.php?page=ws-news-alerts/ws-news-alerts.php">'.__('Manager','wsna').'</a>';
	return $links;
}

// Add menu to options page
function WSNA_add_options_page()
{
	global $user_level;
	
	// Only Administrator can see this page
	if (function_exists('add_users_page'))
	{
		add_users_page(__('News Alerts Manager', 'wsna'), __('News Alerts Manager', 'wsna'), 'manage_options', 'ws-news-alerts/ws-news-alerts.php', 'WSNA_user_manager');
	}

	// Only Subscriber can see this page
	//if ( $user_level == 0)
	//{
		if (function_exists('add_menu_page'))
		{
			// About system level: http://codex.wordpress.org/User_Levels
			// About roles and capabilities:http://codex.wordpress.org/Roles_and_Capabilities
			add_menu_page(__('News Alerts', 'wsna'), __('News Alerts', 'wsna'), 'level_0', 'ws-news-alerts/alerts-manager.php');
		}
	//}
}

// Add stylesheet and javascript
function WSNA_admin_head()
{
  $url = get_settings('siteurl');
  $ui_core = $url . '/wp-includes/js/jquery/ui.core.js';
  $ui_tabs = $url . '/wp-includes/js/jquery/ui.tabs.js';
  echo '<!-- WS News Alerts -->
	<link type="text/css" rel="stylesheet" href="'. WSNA_URLPATH  .'style.css" media="all" />
	<script type="text/javascript" src="' . $ui_core . '"></script>
	<script type="text/javascript" src="' . $ui_tabs . '"></script>
	<script type="text/javascript">
			jQuery(function() {
			jQuery(\'#WSNA-wrap > ul\').tabs();});
	</script>'."\n\t";
  echo '<!-- /WS News Alerts-->'."\n";
}


// Matching keywords
function WSNA_matching_keywords($post_ID)
{
	$the_post = get_postdata($post_ID);
	$content = strtolower($the_post['Content']);

	$alerts = WSNA_get_alerts();
	$alert_keyword = array();

	foreach ( $alerts as $item )
	{
		//array_push($alert_keyword, preg_split('/\s+/', $item->alert_keywords));
		array_push($alert_keyword, split('[(\s+)|,(\s+)]', $item->alert_keywords));
	}

	$output ='';
	$result = array();
	$step = 0;

	// For every string in our batch ...
	foreach( $alert_keyword as $item )
	{
		foreach( $item as $key )
		{
			if(is_int(strpos($content, $key, $step)))
			{
				array_push($result, $key);
			}
			$step++;
		}
	}

	// Found it and send mail
	if(sizeof($result) > 0)
	{
		$post_title = $the_post['Title'];
		$post_link = get_permalink($post_ID);
		$keywords = implode(', ', $result);
		WSNA_send_mail($keywords, $post_title, $post_link);
	}

   return $content;
}


function WSNA_user_info()
{
	global $current_user;
	get_currentuserinfo();
	
	$user['id'] = $current_user->user_ID;
	$user['name'] = $current_user->user_login;
	$user['first_name'] = $current_user->user_firstname;
	$user['last_name'] = $current_user->user_lastname;
	$user['display'] = $current_user->display_name;
	$user['level'] = $current_user->user_level;
	switch ( $user['level'] )
	{
		case 10:
			$user['role'] = __('Administrator', 'wsna');
			break;
		case 7:
			$user['role'] = __('Editor', 'wsna');
			break;
		case 2:
			$user['role'] = __('Author', 'wsna');
			break;
		case 1:
			$user['role'] = __('Contributor', 'wsna');
			break;
		case 0:
			$user['role'] = __('Subscriber', 'wsna');
			break;
	}
	
	return $user;
}

// Delete  user & alert inforations
function WSNA_delete_user( $user_id )
{
	global $wpdb;

	$result = $wpdb->query
	(
		"DELETE FROM $wpdb->users WHERE $wpdb->users.ID=$user_id"
	);

	$result = $wpdb->query
	(
		"DELETE FROM `ws_news_alerts` WHERE `ws_news_alerts`.user_id=$user_id"
	);

	return ture;
}

function WSNA_alert_count($user_id=null)
{
	global $wpdb, $user_ID;
	
	$user_id = (empty($user_id))?$user_ID:$user_id;

	$all_alert_count = $wpdb->get_col
	(
		"SELECT $wpdb->users.user_alerts FROM $wpdb->users WHERE ID=$user_id"
	);
	$count['all'] = empty($all_alert_count[0])?'NA':$all_alert_count[0];
	
	$used_alert_count = $wpdb->get_col
	(
		"SELECT COUNT(alert_categorie) FROM ws_news_alerts WHERE user_id=$user_id"
	);
	$count['used'] = empty($used_alert_count[0])?'0':$used_alert_count[0];
	return $count;
}

// Add alert to user
function WSNA_add_alert($categorie, $keywords)
{
	global $wpdb, $user_ID, $status;
	$alert_count = WSNA_alert_count();
	if ( $alert_count['used']>=$alert_count['all'] )
	{
		$status['error'] = __('Categorie number is maximum of your account.', 'wans');
		return false;
	}
	
	$alert_keyword = array();
	$alert_keyword = preg_split('/([,(\s+)|(\s+)])+/', $keywords);
	$keywords = implode(', ', $alert_keyword);
	
	$result = $wpdb->get_results
	(
		"SELECT * FROM `ws_news_alerts` WHERE `user_id`=$user_ID AND `alert_categorie`=\"$categorie\""
	);
	
	if ( empty($result) )
	{
		//New record
		$result = $wpdb->query
		(
			"INSERT INTO `ws_news_alerts` (`user_id`, `alert_categorie` , `alert_keywords`) VALUES ('$user_ID', '$categorie', '$keywords')"
		);
	}
	else
	{
		// Alert old record
		$alert_id = $result[0]->alert_id;
		$keywords = $result[0]->alert_keywords.', '.$keywords;
		$result = $wpdb->query
		(
			"UPDATE `ws_news_alerts` SET `alert_keywords`=\"$keywords\" WHERE `alert_id`=$alert_id"
		);
	}
	
	$status['update'] = __('Updated. Add "'.$categorie.'" successful!', 'wans');
	return true;
}

// Delete alert to user
function WSNA_delete_alert( $alert_id )
{
	global $wpdb, $user_ID;

	$result = $wpdb->query
	(
		"DELETE FROM `ws_news_alerts` WHERE `ws_news_alerts`.`alert_id` = $alert_id"
	);
	return ture;
}

// Show all users of add News Alerts informations
function WSNA_list_users()
{
	global $wpdb;

	$query = $wpdb->get_results
	(
		"SELECT ws_news_alerts.alert_id,alert_keywords,$wpdb->users.ID,user_login,user_email,user_alerts
		FROM ws_news_alerts,$wpdb->users WHERE ws_news_alerts.user_id=$wpdb->users.ID OR $wpdb->users.ID
		GROUP BY $wpdb->users.user_email ASC"
	);
	
	return $query;
}

// Show user alerts
function WSNA_list_alerts($user_id=null)
{
	global $wpdb, $user_ID;
	
	$user_id =(empty($user_id) || !is_int($user_id))?$user_ID:$user_id;	
	$query = $wpdb->get_results
	(
		"SELECT ws_news_alerts.* FROM ws_news_alerts,$wpdb->users 
		WHERE ws_news_alerts.user_id=$user_id
		GROUP BY ws_news_alerts.alert_id ASC"
	);
	
	return $query;
}

// Send email to user
function WSNA_send_mail($keywords, $post_title, $post_link)
{
		global $user_email,$user_identity;

		if( empty($post_title) && empty($post_link) )
			return;

		// strip out some chars that might cause issues, and assemble vars
		$site_name = str_replace('"', "'", get_bloginfo('name'));
		$site_email = str_replace(array('<', '>'), array('', ''), get_bloginfo('admin_email'));

		$subject = __('News Alert from ', 'wsna') . $site_name;
		$message = 'Hello '.$user_identity.', Here have a news alert whitch you pay attention to it.
			Keywords is :' . $keywords . ' and title: '.$post_title.' and Link is: '.$post_link;

		$charset = get_settings('blog_charset');
		$headers  = "From: \"{$site_name}\" <{$site_email}>\n
			MIME-Version: 1.0\n
			Content-Type: text/html; charset=\"{$charset}\"\n
			Article link: " . $post_link;

		return wp_mail($user_email, $subject, $message, $headers);
}

// User manager page
function WSNA_user_manager()
{
	$info = new WSNA_Info;
	
	if( isset($_GET['action']) && ($_GET['action'] == 'deleteUser'))
	{
		WSNA_delete_user($_GET['user_id']);
	}
?>
<div class="wrap">
	<form id="posts-filter" method="get" action="">
		<h2><?php echo __('News Alerts Manager', 'wsna'); ?></h2>
		<?php if ($NewVersion): ?>
		<div class="updated">
			<p>
				<?php echo __('There is a new version available.', 'wsna'); ?>
				<a class="thickbox" href="plugin-install.php?tab=plugin-information&plugin=ws-news-alerts&TB_iframe=true&width=640&height=712">
					View lastest version Details
				</a> or 
				<a href="#">
					upgrade automatically
				</a>.
			</p>
		</div>
		<?php endif ?>

		<br class="clear"/>
		<div id="WSNA-wrap">
			<ul class="ui-tabs-nav">
				<li class="ui-tabs-selected"><a href="#WSNA-categories"><span><?php echo __('Users', 'wsna') ?></span></a></li>
				<li><a href="#WSNA-settings"><span><?php echo __('Settings', 'wsna') ?></span></a></li>
				<li><a href="#WSNA-uninstall"><span><?php echo __('Uninstall', 'wsna') ?></span></a></li>
			</ul>

			<div style="display:block" class="ui-tabs-panel" id="WSNA-categories">
				<table class="widefat">
					<thead>
					<tr>
						<th class="check-column" scope="col"><input type="checkbox" onclick="CheckAll(document.getElementById('posts-filter'));" /></th>
						<th scope="col"><?php echo __('Username', 'wsna') ?></th>
						<th scope="col"><?php echo __('Email', 'wsna') ?></th>
						<th class="num" scope="col"><?php echo __('Current Alerts', 'wsna') ?></th>
						<th class="num" scope="col"><?php echo __('Maximum Alerts', 'wsna') ?></th>
						<th class="action-links" scope="col"><?php echo __('Options', 'wsna') ?></th>
					</tr>
					</thead>
					<tbody class="list:cat" id="the-list">
					<?php 
						$users = WSNA_list_users(); 
						foreach ( $users as $user )
						{
							$alert_count = WSNA_alert_count($user->ID);
							$style = ($alert_count['all']==$alert_count['used'])?' class="unapproved"':'';
							echo '<tr id="cat-'.$user->ID.'" '.$style.'>
								<th class="check-column" scope="row"><input type="checkbox" value="4" name="delete[]"/></th>
								<td class="col">'.$user->user_login.'</td>
								<td class="col">'.$user->user_email.'</td>
								<td class="num">'.$alert_count['used'].'</td>
								<td class="num">'.$user->user_alerts.'</td>
								<td class="action-links" scope="col">
								<a class="delete" href="users.php?page=ws-news-alerts/ws-news-alerts.php&action=deleteUser&user_id='.$item->ID.'">'.__('Delete', 'wsna').'</a></td>
								</tr>';
						}
					?>
					</tbody>
				</table>

				<div class="tablenav options">
					<a href="#" class="button"><?php echo __('Delete User(s)', 'wsna') ?></a>
					<a href="user-new.php" class="button"><?php echo __('Add User(s)', 'wsna') ?></a>
					<br class="clear"/>
				</div>
			</div>

			<div class="ui-tabs-panel ui-tabs-hide" id="WSNA-settings">
				<table class="form-table">
					<tr valign="top">
						<th scope="row">Default News Alerts</th>
						<td><input type="text" /></td>
					</tr>
					<tr valign="top">
						<th scope="row">Register</th>
						<td><input type="checkbox" value="yes" />yes <input type="checkbox" value="no" />no</td>
					</tr>
				</table>
				<p class="submit"><input type="submit" value="<?php echo __('Save Options', 'wsna'); ?>" name="submit" class="button"/></p>
			</div>

			<div class="ui-tabs-panel ui-tabs-hide" id="WSNA-uninstall">
				<p>Do you want to uninstall WS News Alerts?</p>
				<p>Note:It will delete ALL user informations!!</a>
				<p class="submit"><input type="submit" value="<?php echo __('UNINSTALL', 'wsna'); ?>" name="submit" class="button"/></p>
			</div>
			<br class="clear"/>
		</div>
	</form>
	<script type="text/javascript">
	function CheckAll(form)
	{
		for (i = 0, n = form.elements.length; i < n; i++)
		{
			if(form.elements[i].type == "checkbox" && !(form.elements[i].getAttribute('onclick',2)))
			{
				if(form.elements[i].checked == true)
				{
					form.elements[i].checked = false;
				}
				else
				{
					form.elements[i].checked = true;
				}
			}
		}
	}
	</script>
	
	<div class="tablenav">
		<div class="alignleft" style="padding-top:5px;">
			<?php echo $info->name.' v'.$info->version.' by <a href="'.$info->plugin.'" target="_blank">'.$info->author.'</a> | <a href="'.$info->url.'" target="_blank">'.__('What\'s this', 'wsna').'</a>?' ?>
		</div>
		<br class="clear"/>
	</div>
</div>

<?php
}
?>
